﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;

namespace ProjectBuilder
{
    [DbTable("phpdoc_folder")]
    public class Folder : BaseDocObject
    {
        /// <summary>
        /// Ім'я каталогу
        /// </summary>
        [DbField("name")]
        public string Name { get; set; }

        /// <summary>
        /// Ім'я каталогу
        /// </summary>
        [DbField("parent_id")]
        public long? ParentId { get; set; }

        public Folder(string path)
        {
            string[] parts = path.Split('/');
            ParentId = getRoot();
            long? prev = getRoot();
            for (int i = 1; i < parts.Length - 1; i++)
            {
                Name = parts[i];
                prev = ParentId;
                ParentId = getDBId();
            }
            _dbId = ParentId;
            ParentId = prev;            
        }

        public long? getRoot()
        {
            var cmd = new MySqlCommand();
            cmd.CommandText = "SELECT id FROM `" + this.getAttribute<DbTableAttribute>().TableName + "` WHERE `parent_id` IS NULL";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = Globals.Connection;
            var res = cmd.ExecuteScalar();
            if (res != null)
                return long.Parse(cmd.ExecuteScalar().ToString());

            cmd.CommandText = "INSERT INTO `" + this.getAttribute<DbTableAttribute>().TableName + "` (`name`) VALUES ('')";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = Globals.Connection;
            cmd.ExecuteNonQuery();
            return 1;
        }

        public long? getDBId()
        {
            var cmd = new MySqlCommand();
            cmd.CommandText = "SELECT id FROM `" + this.getAttribute<DbTableAttribute>().TableName + "` WHERE `parent_id` = '" + ParentId + "' && `name` = '" + Name + "'";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = Globals.Connection;
            var res = cmd.ExecuteScalar();
            if (res != null)
                return long.Parse(cmd.ExecuteScalar().ToString());

            cmd.CommandText = "INSERT INTO `" + this.getAttribute<DbTableAttribute>().TableName + "` (`parent_id`,`name`) VALUES (" + ParentId + ", '" + Name + "')";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = Globals.Connection;
            cmd.ExecuteNonQuery();
            cmd.CommandText = "SELECT id FROM `" + this.getAttribute<DbTableAttribute>().TableName + "` WHERE `parent_id` = '" + ParentId + "' && `name` = '" + Name + "'";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = Globals.Connection;
            return long.Parse(cmd.ExecuteScalar().ToString());
        }
    }
}
